package com.yunda.AJDeviceService.common.web.exception;

import com.yunda.AJDeviceService.common.web.domain.AjaxResult;
import com.yunda.AJDeviceService.common.web.domain.ErlangsAjaxResult;
import lombok.extern.slf4j.Slf4j;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 *
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler
{
    @ExceptionHandler(Exception.class)
    public AjaxResult error(Exception e){
        log.error(e.getMessage(),e);
        return AjaxResult.error(999, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleMethodArgumentNotValidExctpton(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        StringBuilder errMsg = new StringBuilder(bindingResult.getFieldErrors().size() * 16);
        errMsg.append("Invalid Request：");
        for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
            if (i > 0) {
                errMsg.append(",");
            }
            FieldError error = bindingResult.getFieldErrors().get(i);
            errMsg.append(error.getField());
            errMsg.append(":");
            errMsg.append(error.getDefaultMessage());
        }

        AjaxResult respEntity = AjaxResult.error(999, errMsg.toString());
        return respEntity;
    }}
